package com.huadi.android.ainiyo.activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArraySet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.huadi.android.ainiyo.R;
import com.huadi.android.ainiyo.util.CONST;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONException;
import org.json.JSONObject;


import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.huadi.android.ainiyo.application.ECApplication.sessionId;

public class EditHobbyActivity extends AppCompatActivity {

    @ViewInject(R.id.edit_hobby)
    EditText edit_hobby;
    @ViewInject(R.id.edit_hobby_text_num)
    TextView edit_hobby_text_num;
    @ViewInject(R.id.tag_flow)
    TagFlowLayout tagFlowLayout;

    private TagFlowLayout mFlowLayout;
    private String[] mVals = CONST.HOBBY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_hobby);

        ViewUtils.inject(this);

        final LayoutInflater mInflater = LayoutInflater.from(this);

        tagFlowLayout.setAdapter(new TagAdapter<String>(mVals) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.tag_textview,
                        tagFlowLayout, false);
                tv.setText(s);
                return tv;
            }
        });
//        edit_hobby.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
//
//                String content = edit_hobby.getText().toString();
//                edit_hobby_text_num.setText(String.valueOf(50 - content.length()));
//            }
//
//            @Override
//            public void afterTextChanged(Editable editable) {
//
//            }
//        });
        Intent intent = getIntent();
        String text = intent.getStringExtra("hobby");
        SetTagByText(text);
        edit_hobby.setText(text);

    }

    private void SetTagByText(String text) {
        String[] tags = text.split(" ");//空格分割
        //Toast.makeText(this,tags[0],Toast.LENGTH_SHORT).show();
        Set<Integer> selected = new HashSet<>();
        List<String> temp = Arrays.asList(mVals);

        for (String tag : tags
                ) {

            int pos = temp.indexOf(tag);
            if (pos >= 0) {
                selected.add(pos);
            }

            Log.d("TagSys", tag);
            //Toast.makeText(this,String.valueOf(Arrays.binarySearch(mVals,tag)),Toast.LENGTH_SHORT).show();
        }

        tagFlowLayout.getAdapter().setSelectedList(selected);
    }

    private String GetTextByTag() {
        StringBuffer result = new StringBuffer();
        for (Integer pos : tagFlowLayout.getSelectedList()
                ) {
            result.append(" " + mVals[pos] + " ");
        }
        return result.toString();
    }

    @OnClick({R.id.edit_hobby_publish, R.id.edit_hobby_back})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_hobby_publish:
                edit_hobby.setText(GetTextByTag());
                //Toast.makeText(this,edit_hobby.getText(),Toast.LENGTH_SHORT).show();

                if (TextUtils.isEmpty(edit_hobby.getText())) {
                    Toast.makeText(this, "请选择至少一个兴趣", Toast.LENGTH_SHORT).show();
                }
                else {
                    RequestParams params = new RequestParams();
                    params.addBodyParameter("sessionid", sessionId);
                    params.addBodyParameter("hobby", edit_hobby.getText().toString());
                    new HttpUtils().send(HttpRequest.HttpMethod.POST, "http://120.24.168.102:8080/modifyhobby", params, new RequestCallBack<String>() {
                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            try {
                                JSONObject object = new JSONObject(responseInfo.result.toString());
                                int status = object.getInt("Status");
                                String result = object.getString("Result");
                                String msg = object.getString("Msg");

                                Intent resultIntent = new Intent();
                                resultIntent.putExtra("data_return",edit_hobby.getText().toString());
                                setResult(RESULT_OK,resultIntent);
                                finish();



                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(HttpException error, String msg) {
                            finish();

                            Toast.makeText(EditHobbyActivity.this, "连接错误", Toast.LENGTH_SHORT).show();

                        }
                    });
                }
                break;
            case R.id.edit_hobby_back:
                finish();
                break;
        }
    }
}
